package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.CommodtiyDetails;
import com.wanglibao.woodtrade.woodtrade.entity.GetFileName;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseEntity;
import com.wanglibao.woodtrade.woodtrade.entity.ResponsePictrueNameEntity;
import com.wanglibao.woodtrade.woodtrade.entity.UploadRetrueEntity;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.adapter.ItemImgvRvCommodityAdapter;
import com.wanglibao.woodtrade.woodtrade.util.ConserveImage;
import com.wanglibao.woodtrade.woodtrade.util.GetPicPath;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.SVGridView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

@SuppressLint("SdCardPath")
public class EditCommodityActivity extends BaseActivity implements AdapterView.OnItemClickListener {


    @Bind(R.id.edit_title_edit_commodity)
    EditText mEditTitleEditCommodity;
    @Bind(R.id.tv_hongxian)
    TextView mTvHongxian;
    @Bind(R.id.rv_editCommodity_activity)
    SVGridView mRvEditCommodityActivity;
    @Bind(R.id.tv_activity_release_demand_type)
    TextView mTvActivityReleaseDemandType;
    @Bind(R.id.edit_activity_release_demand_size)
    EditText mEditActivityReleaseDemandSize;
    @Bind(R.id.edit_activity_release_demand_dengji)
    EditText mEditActivityReleaseDemandDengji;
    @Bind(R.id.edit_activity_release_demand_chandi)
    TextView mEditActivityReleaseDemandChandi;
    @Bind(R.id.edit_activity_release_demand_shangjialiang)
    EditText mEditActivityReleaseDemandShangjialiang;
    @Bind(R.id.edit_activity_release_demand_qidingliang)
    EditText mEditActivityReleaseDemandQidingliang;
    @Bind(R.id.tv_activity_release_demand_order_cangchudi)
    TextView mTvActivityReleaseDemandOrderCangchudi;
    @Bind(R.id.ll_activity_release_info_order_number)
    LinearLayout mLlActivityReleaseInfoOrderNumber;
    @Bind(R.id.edit_information_edit_commodity)
    EditText mEditInformationEditCommodity;
    @Bind(R.id.edit_activity_release_demand_price)
    EditText edit_activity_release_demand_price;
    @Bind(R.id.tv_shangjia_edit_commodity)
    TextView mTvShangjiaEditCommodity;
    @Bind(R.id.tv_xiajia_edit_commodity)
    TextView mTvXiajiaEditCommodity;

    @Bind(R.id.ll_activity_edit_commodity_bottom)
    LinearLayout ll_activity_edit_commodity_bottom;
    @Bind(R.id.sl_editor_commodity_activity)
    ScrollView mSlEditorCommodityActivity;
    @Bind(R.id.tv_activity_release_demand_danwei)
    TextView mTvActivityReleaseDemandDanwei;
    //============================
    /*图片的名称*/
    private String IMAGE_FILE_NAME;
    /*相机的请求码*/
    private static final int CAMERA_REQUEST_CODE = 10;
    /*高清图片的文件目录*/
    String cameraPath;
    /*将系统图片转换成 年-月-日 时：分：秒 形式*/
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*从服务器返回图片的名称*/
    String PicName = null;
    /*存放上传成功后，返回json中的fileName*/
    ResponsePictrueNameEntity mNameEntity = null;
    /*存放token的实体类*/
    ResponseEntity mResponseEntity = null;
    /*临时生成的token*/
    String token = null;
    /*生成缩略图片的文件夹*/
    String desName = Environment.getExternalStorageDirectory() + "/wood/commodity";
    String fileName;
    /*访问接口需要拼接的商品ID*/
    String Goods_id;
    String TAG = "EditCommodityActivity";
    /*存放图片的路径*/
    List<String> mUriList;
    List<String> mImageName = new ArrayList<>();
    /*对应的SVGridView的加载图片的适配器*/
    ItemImgvRvCommodityAdapter mAdapter;
    /*商品编辑的信息实体类*/
    CommodtiyDetails mDetails = new CommodtiyDetails();
    /*CustomDialog*/
    ActionSheetDialog dialog;
    private static final int IMAGE_REQUEST_CODE = 0;

    boolean isEdit = true;
    String PictrueUrl;
    UploadRetrueEntity mEntity;
    public static final int TYPE_Goods = 1;
    //图片的名称
    List<String> upLoadFileName = new ArrayList<>();
    Uri uri1;
    Uri uri2;
    String add_Goods_id;
    /*jsonRPC 访问成功的Handler*/
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2) {
                if (msg.arg1 == NetConfig.TaskId.onPutwayDetail) {
                    mDetails = new Gson().fromJson(msg.obj.toString(), CommodtiyDetails.class);
                    AppearView();
                    mAdapter = new ItemImgvRvCommodityAdapter(EditCommodityActivity.this, mUriList, upLoadFileName);
                    mRvEditCommodityActivity.setAdapter(mAdapter);
                }
                if (msg.arg1 == NetConfig.TaskId.onPutwayDetailOperation) {
                    ToastUtil.createLongToast(EditCommodityActivity.this,"修改编辑成功");
                    finish();
                }
                if (msg.arg1 == NetConfig.TaskId.addGoods) {
                    ToastUtil.createLongToast(EditCommodityActivity.this,"上架成功");
                    finish();
                }
            } else {
                ToastUtil.createNormalToast(msg.obj.toString());
            }
            return false;
        }
    }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_edit_commodity);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        initData();
    }

    private void initData() {
        tvTitle.setText("商品编辑详情");
        addViewClicklistener(tvBack, mTvShangjiaEditCommodity, mTvXiajiaEditCommodity);
        mRvEditCommodityActivity.setOnItemClickListener(this);
        Intent intent = getIntent();

        Goods_id = intent.getStringExtra("goods_id");
        add_Goods_id = getIntent().getStringExtra("Goods_id");
        //编辑
        if (!TextUtils.isEmpty(Goods_id)) {
            isEdit = true;
            NetWorking();
        } else {
            //新增
            mAdapter = new ItemImgvRvCommodityAdapter(this, new ArrayList<String>(), upLoadFileName);
            mRvEditCommodityActivity.setAdapter(mAdapter);
            isEdit = false;
            String dopt = intent.getStringExtra("dopt");
            String woodType = intent.getStringExtra("woodType");
            String unit=intent.getStringExtra("unit");
            String place=intent.getStringExtra("place");
            mTvActivityReleaseDemandType.setText(woodType);
            mTvActivityReleaseDemandOrderCangchudi.setText(dopt);
            mTvXiajiaEditCommodity.setVisibility(View.GONE);
            mTvActivityReleaseDemandDanwei.setText(unit);
            mEditActivityReleaseDemandChandi.setText(place);
            SelectDanwei();
        }
        if (!isEdit) {
            mUriList = new ArrayList<>();
            mUriList.add("");
        }

        if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = getWindow().getDecorView();
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect rect = new Rect();
                    decorView.getWindowVisibleDisplayFrame(rect);
                    int screenHeight = decorView.getRootView().getHeight();
                    int height = screenHeight - rect.bottom;
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_activity_edit_commodity_bottom.getLayoutParams();
                    layoutParams.setMargins(0, 0, 0, height);
                    ll_activity_edit_commodity_bottom.requestLayout();
                }
            });
        }
    }

    /*jsonRPC联网*/
    private void NetWorking() {
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_GOODS,
                NetConfig.onPutwayDetail, mHandler,
                "jsonObject", NetConfig.TaskId.onPutwayDetail, new Object[]{String.valueOf(Goods_id), new UserImpl(this).getUser().token});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }


    /*联网完成后调用，将数据展现在不同的View控件上面*/
    private void AppearView() {
        mEditTitleEditCommodity.setText(mDetails.getTitle());
        mTvActivityReleaseDemandType.setText(mDetails.getCategory_name());
        mEditActivityReleaseDemandSize.setText(mDetails.getSize());
        mEditActivityReleaseDemandDengji.setText(mDetails.getRank());
        mEditActivityReleaseDemandChandi.setText(mDetails.getPlace());
        edit_activity_release_demand_price.setText(mDetails.getPrice());
        mEditActivityReleaseDemandShangjialiang.setText(mDetails.getUp_quantity());
        mEditActivityReleaseDemandQidingliang.setText(mDetails.getOrder_number());
        mTvActivityReleaseDemandOrderCangchudi.setText(mDetails.getDepot());
        mEditInformationEditCommodity.setText(mDetails.getGoods_description());
        SelectDanwei();
        mUriList = mDetails.getImg_url();
        // 讲图片的url 截取 获取图片的 名称 添加到upLoadFileName 集合中 传给mAdapter
        if (mUriList.size() != 0) {
            for (String picpictrueUrl : mUriList) {
                upLoadFileName.add(SubString(picpictrueUrl));
            }
        }
    }
    public void SelectDanwei(){
        if(isEdit){
//            //编辑的时候 在这里
//            if("2".equals(mDetails.getUnit().toString())){
//
//                mTvActivityReleaseDemandDanwei.setText("立方米");
//            }else if("3".equals(mDetails.getUnit().toString())) {
//                mTvActivityReleaseDemandDanwei.setText("千克");
//                UnitState=true;
//                UnitState1=false;
//                mTvActivityReleaseDemandDanwei.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showDialog();
//                    }
//                });
//            }else if("1".equals(mDetails.getUnit().toString())){
//                mTvActivityReleaseDemandDanwei.setText("吨");
//                UnitState=false;
//                UnitState1=true;
//                mTvActivityReleaseDemandDanwei.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showDialog();
//                    }
//                });
//            }
        }else {
            // 新增商品的时候在这里
            if(mTvActivityReleaseDemandDanwei.getText().toString().equals("千克")&&!isEdit){
                UnitState=true;
                UnitState1=false;
                mTvActivityReleaseDemandDanwei.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog();
                    }
                });
            }
            if(mTvActivityReleaseDemandDanwei.getText().toString().equals("吨")&&!isEdit){
                UnitState=false;
                UnitState1=true;
                mTvActivityReleaseDemandDanwei.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog();
                    }
                });
            } if(mTvActivityReleaseDemandDanwei.getText().toString().equals("立方米")&&!isEdit){
            }
        }

    }
    Dialog dialog1;
    boolean UnitState=false;
    boolean UnitState1=false;
    Double shuliang;
    Double shuliang1;

    private void showDialog() {
        dialog1 = new Dialog(this, R.style.dialog_bgTransparent);
        dialog1.setCanceledOnTouchOutside(true);
        dialog1.show();
        dialog1.getWindow().setContentView(R.layout.dropdownlist_view);
        TextView tv_title = (TextView) dialog1.findViewById(R.id.tv_dialog_title);
        tv_title.setText("请选择单位");
        TextView tv_cancle = (TextView) dialog1.findViewById(R.id.tv_dialog_tel_cancle);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
                mTvActivityReleaseDemandDanwei.setText("吨");
//                if(UnitState){
//                    UnitState1=true;
//                    UnitState=false;
//                    String string=mEditActivityReleaseDemandShangjialiang.getText().toString();
//                    if(!string.equals("")){
//                        shuliang=round(Double.valueOf(string)*0.001,3);
//                        mEditActivityReleaseDemandShangjialiang.setText(shuliang+"");
//                    }else {
//                        ToastUtil.createNormalToast("请填写上架量");
//                    }
//                    String string1=mEditActivityReleaseDemandQidingliang.getText().toString();
//                    if(!string1.equals("")){
//                        shuliang1=round(Double.valueOf(string1)*0.001,3);
//                        mEditActivityReleaseDemandQidingliang.setText(shuliang1+"");
//                    }else {
//                        ToastUtil.createNormalToast("请填写起订量");
//                    }
//
//                }else {
//
//                }

            }
        });
        TextView tv_tel = (TextView) dialog1.findViewById(R.id.tv_dialog_call);
        tv_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
                mTvActivityReleaseDemandDanwei.setText("千克");
                String string1;
//                if(UnitState1){
//                    UnitState=true;
//                    UnitState1=false;
//                    String string0=mEditActivityReleaseDemandShangjialiang.getText().toString();
//                    if(!string0.equals("")){
//                        shuliang=Double.valueOf(string0)*1000;
//                        string1=String.valueOf(shuliang);
//                        String string2=string1.substring(0,string1.lastIndexOf("."));
//                        mEditActivityReleaseDemandShangjialiang.setText(string2);
//
//                    }else {
//                        ToastUtil.createNormalToast("请填写上架量");
//                    }
//
//                    String string5=mEditActivityReleaseDemandQidingliang.getText().toString();
//                    if(!string5.equals("")){
//                        shuliang1=Double.valueOf(string5)*1000;
//                        String string3=String.valueOf(shuliang1);
//                        String string4=string3.substring(0,string3.lastIndexOf("."));
//                        mEditActivityReleaseDemandQidingliang.setText(string4);
//                    }else {
//                        ToastUtil.createNormalToast("请填写起架量");
//                    }
//
//                }else {
//                }
            }
        });
    }
    /**
     * 提供精确的小数位四舍五入处理。
     * @param v 需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static double round(double v,int scale){
        if(scale<0){
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public String SubString(String pictrueUrl) {
        String string = pictrueUrl;
        int i = string.indexOf("file=");
        int i1 = string.lastIndexOf("&");
        String s = string.substring(i + 5, i1);
        return s;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (position == (mAdapter.mPicName.size()) && mUriList.size() > 0) {
            fileName = format.format(new Date()) + "compress" + ".jpg";
            IMAGE_FILE_NAME = System.currentTimeMillis() + ".jpg";
            OkHttpUtils.post().addParams("access_key", NetConfig.ACCESS_KEY)
                    .addParams("secret_key", NetConfig.SECRET_KEY)
                    .url(NetConfig.ACHIEVE_TOKEN_URL)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                        }

                        @Override
                        public void onResponse(String response) {
                            mResponseEntity = new Gson().fromJson(response, ResponseEntity.class);
                            token = mResponseEntity.getToken();
                        }
                    });
            ActionSheetDialogNoTitle();
        }
    }

    private void ActionSheetDialogNoTitle() {
        final String[] stringItems = {"拍照", "选择本地相册"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        requestPermission();
                        SelectPictrueFromCamera();
                        break;
                    case 1:
                        requestPermission();
                        SelectPictrueFromSdCard();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /*
   * 选择照片 通过系统相册 从SdCard
   */
    public void SelectPictrueFromSdCard() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*"); // 设置文件类型
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
        dialog.dismiss();
    }

    /*选择照片 通过系统相机进行拍照*/
    public void SelectPictrueFromCamera() {
        dialog.dismiss();
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory().getPath()
                        + "/wood/commodity/");
                if (!file.exists()) file.mkdirs();
                //指定保存路径
                cameraPath = Environment.getExternalStorageDirectory().getPath()
                        + "/wood/commodity/" + format.format(new Date()) + ".jpg";
                File imageFile = new File(cameraPath);
                Uri imageFileUri = Uri.fromFile(imageFile);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(EditCommodityActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(EditCommodityActivity.this, "没有储存卡", Toast.LENGTH_LONG).show();
        }
    }

    int take;

    /*拍照完成后返回，对图片进行压缩比例，上传图片，并且展示*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        } else {
            if (requestCode == CAMERA_REQUEST_CODE) {
                File file1 = ConserveImage.compressImage(cameraPath, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                uri1 = Uri.fromFile(file1);
                take = 0;
                upLoadPictrue(file1);

            }
            if (requestCode == IMAGE_REQUEST_CODE) {
                Uri uri = data.getData();
                String string = uri.getPath();
                String path;
                if (Build.VERSION_CODES.KITKAT >= 19) {  // 或者 android.os.Build.VERSION_CODES.KITKAT这个常量的值是19
                    path = new GetPicPath().getPath_above19(EditCommodityActivity.this, uri);
                    System.out.println("path_above19:" + path);
                } else {
                    path = getFilePath_below19(uri);

                }
                File file2 = ConserveImage.compressImage(path, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                uri2 = Uri.fromFile(file2);
                take = 1;
                upLoadPictrue(file2);

            }
        }
    }

    public static final int EXTERNAL_STORAGE_REQ_CODE = 10;

    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);
            }
        } else {
        }
    }

    /**
     * API19以下获取图片路径的方法
     *
     * @param uri
     */
    private String getFilePath_below19(Uri uri) {
        //这里开始的第二部分，获取图片的路径：低版本的是没问题的，但是sdk>19会获取不到
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
        //获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        System.out.println("***************" + column_index);
        //将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        //最后根据索引值获取图片路径   结果类似：/mnt/sdcard/DCIM/Camera/IMG_20151124_013332.jpg
        String path = cursor.getString(column_index);
        System.out.println("path:" + path);
        return path;
    }

    /**
     * @param file 上传的图片
     */
    public void upLoadPictrue(final File file) {
        if (token != null) {
            OkHttpUtils.post()
                    .addParams("token", token)
                    .addFile("filename", IMAGE_FILE_NAME, file)
                    .url(NetConfig.PICTRUE_UPLOAD_URL)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                        }

                        @Override
                        public void onResponse(String response) {
                            mNameEntity = new Gson().fromJson(response, ResponsePictrueNameEntity.class);
                            GetFileName getFileName1=new Gson().fromJson(mNameEntity.getErr_msg(),GetFileName.class);
                            PicName=getFileName1.getFilename().getName();
                            mAdapter.addDataTomPicName(0,PicName);
                            if(take==0){
                                mAdapter.addData(0, String.valueOf(uri1));
                            } else {
                                mAdapter.addData(0, String.valueOf(uri2));
                            }

                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_shangjia_edit_commodity:
                if (!TextUtils.isEmpty(mEditTitleEditCommodity.getText().toString()) &&
                        !TextUtils.isEmpty(mEditActivityReleaseDemandSize.getText().toString()) &&
                        !TextUtils.isEmpty(mEditActivityReleaseDemandDengji.getText().toString()) &&
                        !TextUtils.isEmpty(mEditActivityReleaseDemandChandi.getText().toString()) &&
                        !TextUtils.isEmpty(edit_activity_release_demand_price.getText().toString()) &&
                        !TextUtils.isEmpty(mEditActivityReleaseDemandShangjialiang.getText().toString()) &&
                        !TextUtils.isEmpty(mEditInformationEditCommodity.getText().toString()) &&
                        !TextUtils.isEmpty(mEditActivityReleaseDemandQidingliang.getText().toString())) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String pictrueName : mAdapter.mPicName) {
                        stringBuffer.append(pictrueName).append(",");
                    }
                    String string = TextUtils.isEmpty(stringBuffer.toString()) ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1);
                    if(!(string.length()>0)){
                        ToastUtil.createNormalToast("商品的图片不能为空");
                    }else {
                        if (isEdit) { //调用商品修改的接口 onPutwayDetailOperation
                            if(Double.valueOf(mEditActivityReleaseDemandShangjialiang.getText().toString())>=1&&Double.valueOf(mEditActivityReleaseDemandQidingliang.getText().toString())>=1){
                                submitUpdate("1");
                            }else {
                                ToastUtil.createNormalToast("上架量或起订量数字必须大于1");
                            }
                        } else { //调用商品上架的接口addGoods
                            if(Double.valueOf(mEditActivityReleaseDemandShangjialiang.getText().toString())>=1&&Double.valueOf(mEditActivityReleaseDemandQidingliang.getText().toString())>=1){
                                submitAdd();
                            }else {
                                ToastUtil.createNormalToast("上架量或起订量数字必须大于1");
                            }
                        }
                    }

                } else {
                    ToastUtil.createLongToast(this, "资料不完整");
                }

                break;
            case R.id.tv_xiajia_edit_commodity:
                submitUpdate("0");
                break;
            default:
                break;
        }
    }
    /**
     * 编辑按钮的 商品上、下架操作
     *
     * @param type 上架 "1" 或者 下架 "1"
     */
    private void submitUpdate(String type) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goods_id", Goods_id);
            jsonObject.put("token", new UserImpl(this).getUser().token);
            jsonObject.put("putaway", type);
            if(Double.valueOf(mEditActivityReleaseDemandShangjialiang.getText().toString())>=1){
                jsonObject.put("up_quantity", mEditActivityReleaseDemandShangjialiang.getText());
            }else {
                ToastUtil.createNormalToast("上架量数字必须大于1");
            }
            if(Double.valueOf(mEditActivityReleaseDemandQidingliang.getText().toString())>=1){
                jsonObject.put("order_number", mEditActivityReleaseDemandQidingliang.getText());

            }else {
                ToastUtil.createNormalToast("起定量数字必须大于1");
            }
            jsonObject.put("title", mEditTitleEditCommodity.getText());
            jsonObject.put("place", mEditActivityReleaseDemandChandi.getText());
            jsonObject.put("rank", mEditActivityReleaseDemandDengji.getText());
            jsonObject.put("size", mEditActivityReleaseDemandSize.getText());
            jsonObject.put("goods_description", mEditInformationEditCommodity.getText());
            jsonObject.put("price", edit_activity_release_demand_price.getText());
            if(mTvActivityReleaseDemandDanwei.getText().toString().equals("吨")){
                jsonObject.put("unit",1);
            }else {
                jsonObject.put("unit",3);
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (String pictrueName : mAdapter.mPicName) {
                stringBuffer.append(pictrueName).append(",");
            }
            String string = TextUtils.isEmpty(stringBuffer.toString()) ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1);
            jsonObject.put("img_name", string);//TODO 在此增加所有新增的图片的名字
            jsonObject.put("img_name", string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_GOODS, NetConfig.onPutwayDetailOperation,
                mHandler, "jsonObject", NetConfig.TaskId.onPutwayDetailOperation, new Object[]{jsonObject});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    /*新建商品的添加上架的操作*/
    public void submitAdd() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goods_id", add_Goods_id);
            if(Double.valueOf(mEditActivityReleaseDemandShangjialiang.getText().toString())>=1){
                jsonObject.put("up_quantity", mEditActivityReleaseDemandShangjialiang.getText());
            }else {
                ToastUtil.createNormalToast("上架量数字必须大于1");
            }
            if(Double.valueOf(mEditActivityReleaseDemandQidingliang.getText().toString())>=1){
                jsonObject.put("order_number", mEditActivityReleaseDemandQidingliang.getText());
            }else {
                ToastUtil.createNormalToast("起定量数字必须大于1");
            }
            jsonObject.put("title", mEditTitleEditCommodity.getText());
            jsonObject.put("place", mEditActivityReleaseDemandChandi.getText());
            jsonObject.put("rank", mEditActivityReleaseDemandDengji.getText());

            jsonObject.put("size", mEditActivityReleaseDemandSize.getText());
            jsonObject.put("goods_description", mEditInformationEditCommodity.getText());
            jsonObject.put("price", edit_activity_release_demand_price.getText());
            jsonObject.put("token", new UserImpl(this).getUser().token);
            if(mTvActivityReleaseDemandDanwei.getText().toString().equals("吨")){
                jsonObject.put("unit",1);
            }else {
                jsonObject.put("unit",3);
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (String pictrueName : mAdapter.mPicName) {
                stringBuffer.append(pictrueName).append(",");
            }
            String string = TextUtils.isEmpty(stringBuffer.toString()) ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1);
            jsonObject.put("img_name", string);//TODO 在此增加所有新增的图片的名字
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_GOODS, NetConfig.addGoods,
                mHandler, "jsonObject", NetConfig.TaskId.addGoods, new Object[]{jsonObject});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

}